﻿using Api.Application.Command.UserRole;
using AutoMapper;
using Domain;
using ErrorCode;
using Infrastructure;
using MediatR;
using System.Transactions;

namespace Api.Application.Handler.UserRole
{
    public class AddUserRoleHandler : IRequestHandler<AddUserRoleCommand, ApiResult<int>>
    {
        private readonly IMapper mapper;
        private readonly IBase<UserRoleModel> userRoleRepo;

        public AddUserRoleHandler(IMapper mapper,IBase<UserRoleModel> userRoleRepo)
        {
            this.mapper = mapper;
            this.userRoleRepo = userRoleRepo;
        }
        public async Task<ApiResult<int>> Handle(AddUserRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result=new ApiResult<int>();
            using(TransactionScope tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
         
                try
                {
                    var res = userRoleRepo.GetAll().Where(x => x.RoleId == request.RoleId).ToList();
                    await userRoleRepo.Delete(res);
                    List<UserRoleModel> userRoles=new List<UserRoleModel>();
                    foreach (var item in request.UserId)
                    {
                        userRoles.Add(new UserRoleModel()
                        {
                            UserId=item,
                            RoleId=request.RoleId,
                        });
                    }
                    
                    int count = await  userRoleRepo.AddAsync(userRoles);
                    if (count > 0)
                    {
                        result.Code = ApiEnum.OK;
                        result.Data = count;
                        result.Msg = "分配成功";
                    }
                    else
                    {
                        result.Code = ApiEnum.Fail;
                        result.Data = count;
                        result.Msg = "分配失败";
                    }
                    tran.Complete();
                    return await Task.FromResult(result);
                }
                catch (Exception)
                {

                    throw;
                }
            }
        }
    }
}
